const CartService = require('../../../services/cart.js');
const AddressService = require('../../../services/address');
const storeService = require('../../../services/store.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        cart: [],
        // 购物车表单数据，用于提交订单
        form: [],
        // 全选状态
        isAllSelected: true,
        // 总价
        totalPrice: 0,
        // 选中商品数量
        selectedCount: 0,

        // 地址相关
        defaultAddress: null,
        showAddressForm: false,
        addressForm: {
            name: '',
            phone: '',
            province: '',
            city: '',
            district: '',
            detail: '',
            region: '',
            isDefault: true
        },

        pickUpPointList: [],
        defaultPickUpPoint: null,
        expressType: 'pickUpPoint', // 快递类型 pickUpPoint 自提点 express 快递 
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getCartList();
        this.getDefaultAddress();
        // 获取自提点列表
        this.getPickUpPointList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    /**
     * 获取购物车列表并初始化form数据
     */
    async getCartList(){
        const cartResult = await CartService.getCartList();
        console.log('购物车API返回结果:', cartResult);

        if(cartResult.success && cartResult.data && cartResult.data.list){
            // 验证数据结构
            const validItems = cartResult.data.list.filter(item => {
                if (!item.cart_id) {
                    console.error('❌ 购物车项目缺少id字段:', item);
                    return false;
                }
                if (!item.goods_id) {
                    console.error('❌ 购物车项目缺少goods_id字段:', item);
                    return false;
                }
                if (!item.sku_id) {
                    console.error('❌ 购物车项目缺少sku_id字段:', item);
                    return false;
                }
                return true;
            });
            
            if (validItems.length === 0) {
                console.error('❌ 没有有效的购物车项目');
                wx.showToast({
                    title: '购物车数据异常',
                    icon: 'error'
                });
                return;
            }
            
            // 初始化form数据
            const formData = validItems.map(item => ({
                cart_id: item.cart_id,
                goods_id: item.goods_id,
                sku_id: item.sku_id,
                quantity: item.quantity,
                selected: true, // 默认选中
                goods_name: item.goods_name,
                sku_specs: item.sku_specs,
                sku_price: item.sku_price,
                goods_image: item.goods_image
            }));

            console.log('初始化后的form数据:', formData);

            this.setData({
                cart: { ...cartResult.data, list: validItems },
                form: formData
            });
            
            // 更新选择状态和计算总价
            this.updateSelectionStatus();
        } else {
            console.error('❌ 购物车API返回数据异常:', cartResult);
            wx.showToast({
                title: '获取购物车失败',
                icon: 'error'
            });
        }
    },

    /**
     * 获取自提点列表
     */
    async getPickUpPointList() {
        const result = await storeService.pickUpPointList();
        if (result.success) {
            this.setData({
                pickUpPointList: result.data,
                defaultPickUpPoint: result.data[0] || null
            });
        }
    },

    /**
     * 获取用户默认地址
     */
    async getDefaultAddress() {
        try {
            const result = await AddressService.getAddressList({
                page: 1,
                pageSize: 10,
                showLoading: false
            });
            
            if (result.success && result.data && result.data.list) {
                // 查找默认地址
                const defaultAddress = result.data.list.find(address => address.is_default == 1);
                this.setData({
                    defaultAddress: defaultAddress || null
                });
            }
        } catch (error) {
            console.error('获取默认地址失败:', error);
        }
    },

    /**
     * 数量更改事件处理
     * @param {Object} e 事件对象
     */
    async onQuantityChange(e) {
        const { value } = e.detail;
        const { index } = e.currentTarget.dataset;
        
        if (index === undefined) return;
        
        const cartItem = this.data.cart.list[index];
        const formItem = this.data.form[index];
        
        // 调试信息
        console.log('购物车项目:', cartItem);
        console.log('表单项目:', formItem);
        console.log('使用的cart_id:', formItem.cart_id);
        
        // 验证数据完整性
        if (!formItem || !formItem.cart_id) {
            console.error('❌ 错误: formItem或cart_id为空');
            wx.showToast({
                title: '数据错误，请刷新页面重试',
                icon: 'error'
            });
            return;
        }
        
        if (!cartItem || !cartItem.cart_id) {
            console.error('❌ 错误: cartItem或id为空');
            wx.showToast({
                title: '数据错误，请刷新页面重试',
                icon: 'error'
            });
            return;
        }
        
        // 更新本地数据
        const newForm = [...this.data.form];
        newForm[index].quantity = value;
        
        this.setData({
            form: newForm
        });
        
        // 调用API更新购物车数量
        try {
            const result = await CartService.updateQuantity({
                cart_id: formItem.cart_id,
                quantity: value
            });
            
            if (result.success) {
                // 更新成功，同步更新cart数据
                const newCart = { ...this.data.cart };
                newCart.list[index].quantity = value;
                
                this.setData({
                    cart: newCart
                });
                
                // 重新计算总价
                this.updateSelectionStatus();
                
                wx.showToast({
                    title: '数量更新成功',
                    icon: 'success'
                });
            } else {
                // 更新失败，恢复原数量
                const newForm = [...this.data.form];
                newForm[index].quantity = cartItem.quantity;
                
                this.setData({
                    form: newForm
                });
                
                wx.showToast({
                    title: result.message || '数量更新失败',
                    icon: 'error'
                });
            }
        } catch (error) {
            console.error('更新数量失败:', error);
            
            // 恢复原数量
            const newForm = [...this.data.form];
            newForm[index].quantity = cartItem.quantity;
            
            this.setData({
                form: newForm
            });
            
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'error'
            });
        }
    },

    /**
     * 商品选择事件
     * @param {Object} e 事件对象
     */
    onItemSelect(e) {
        const { index } = e.currentTarget.dataset;
        const newForm = [...this.data.form];
        newForm[index].selected = !newForm[index].selected;
        
        this.setData({
            form: newForm
        });
        
        this.updateSelectionStatus();
    },

    /**
     * 全选/取消全选
     */
    onSelectAll() {
        const newForm = this.data.form.map(item => ({
            ...item,
            selected: !this.data.isAllSelected
        }));
        
        this.setData({
            form: newForm,
            isAllSelected: !this.data.isAllSelected
        });
        
        this.updateSelectionStatus();
    },

    /**
     * 更新选择状态和计算总价
     */
    updateSelectionStatus() {
        const selectedItems = this.data.form.filter(item => item.selected);
        const selectedCount = selectedItems.length;
        const totalPrice = selectedItems.reduce((total, item) => {
            return total + (item.sku_price * item.quantity);
        }, 0);
        const isAllSelected = selectedCount === this.data.form.length && this.data.form.length > 0;
        
        this.setData({
            selectedCount,
            totalPrice: totalPrice.toFixed(2),
            isAllSelected
        });
    },

    /**
     * 选择配送方式
     */
    onExpressTypeChange(e){
        const type = e.currentTarget.dataset.type;
        this.setData({
            expressType: type
        });
    },

    /**
     * 获取选中的商品列表
     */
    getSelectedItems() {
        return this.data.form.filter(item => item.selected);
    },

    /**
     * 计算选中商品总价
     */
    calculateTotalPrice() {
        const selectedItems = this.getSelectedItems();
        return selectedItems.reduce((total, item) => {
            return total + (item.sku_price * item.quantity);
        }, 0);
    },

    /**
     * 提交订单
     */
    async submitOrder() {
        const selectedItems = this.getSelectedItems();
        
        if (selectedItems.length === 0) {
            wx.showToast({
                title: '请选择商品',
                icon: 'error'
            });
            return;
        }
        
        
        // 构建订单数据
        const orderData = {
            items: selectedItems,
            address: this.data.defaultAddress,
            pickUpPoint: this.data.expressType === 'pickUpPoint' ? this.data.defaultPickUpPoint : null,
            expressType: this.data.expressType,
            totalPrice: this.calculateTotalPrice()
        };
        
        const result = await CartService.submit(orderData);

        console.log(result);

        if(result.success){
            // 购买成功后跳转到支付页面
            wx.showLoading({
                title: '去支付...',
                mask: true,
                complete: () => {
                    setTimeout(() => {
                        wx.hideLoading();
                        wx.navigateTo({
                            url: `/store/pages/goods/pay?order_id=${result.data.order_id}`
                        });
                    }, 1000);
                }
            });
        }else{
        }
    }

})